package com.xjcs.saplingplan.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.NotificationCompat
import com.xjcs.saplingplan.MainActivity
import com.xjcs.saplingplan.R
import com.xjcs.saplingplan.enum.FocusType
import com.xjcs.saplingplan.enum.PomodoroPhase
import com.xjcs.saplingplan.model.bean.focus.FocusTimer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class FocusTimerService: Service() {

    private val binder = LocalBinder()
    private var notificationManager: NotificationManager? = null
    private val channelId = "focus_count_channel"
    private val notificationId = 100

    private var wakeLock: PowerManager.WakeLock? = null
    private var timerJob: Job? = null
    private val scope = CoroutineScope(Dispatchers.Default)

    private var timerState: FocusTimer? = null
    var timerUpdateCallback: ((FocusTimer) -> Unit)? = null

    //计时器状态

    inner class LocalBinder: Binder() {
        fun getService(): FocusTimerService = this@FocusTimerService
    }

    override fun onBind(intent: Intent?): IBinder? {
        return binder
    }

    override fun onCreate() {
        super.onCreate()
        notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        createNotificationChannel()
        acquireWakeLock()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "计时器通知",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "计时器运行状态通知"
                setShowBadge(false)
            }
            notificationManager?.createNotificationChannel(channel)
        }
    }

    private fun acquireWakeLock() {
        val powerManager = getSystemService(POWER_SERVICE) as PowerManager
        wakeLock = powerManager.newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK,
            "MultiTimer::TimerWakeLock"
        )
        wakeLock?.acquire(10 * 60 * 1000L) // 10分钟
    }
    fun startTimer(timer: FocusTimer) {
//        timerState = timer.copy(
//            isRunning = true,
//            startTime = System.currentTimeMillis() - timer.pausedTime
//        )

        timerJob?.cancel()
        timerJob = scope.launch {
            while (timerState?.isRunning == true) {
                updateTimer()
                updateNotification()
                delay(1000)
            }
        }
    }

    private fun updateTimer() {
        timerState?.let { timer ->
            val now = System.currentTimeMillis()
            val elapsed = now - timer.startTime

            when (timer.type) {
                FocusType.COUNTDOWN -> {
                    val remaining = timer.totalTime - elapsed
                    if (remaining > 0) {
                        timer.currentTime = remaining
                    } else {
                        timer.currentTime = 0
                        timer.isRunning = false
                        // 倒计时结束处理
                        handleTimerCompletion(timer)
                    }
                }
                FocusType.STOPWATCH -> {
                    timer.currentTime = elapsed
                }
                FocusType.POMODORO -> {
                    val remaining = timer.totalTime - elapsed
                    if (remaining > 0) {
                        timer.currentTime = remaining
                    } else {
                        timer.isRunning = false
                        // 番茄钟阶段切换处理
                        handlePomodoroPhaseChange(timer)
                    }
                }
            }

            timerUpdateCallback?.invoke(timer)
        }
    }

    private fun handleTimerCompletion(timer: FocusTimer) {
        // 播放提示音或震动
        showCompletionNotification(timer)
    }

    private fun handlePomodoroPhaseChange(timer: FocusTimer) {
        timer.pausedTime = 0

        when (timer.pomodoroPhase) {
            PomodoroPhase.WORK -> {
                // 工作结束，进入休息
//                timer.pomodoroPhase = if ((timer.id % 4) == 0) {
//                    PomodoroPhase.LONG_BREAK
//                } else {
//                    PomodoroPhase.SHORT_BREAK
//                }
                timer.totalTime = when (timer.pomodoroPhase) {
                    PomodoroPhase.SHORT_BREAK -> 5 * 60 * 1000 // 5分钟短休息
                    PomodoroPhase.LONG_BREAK -> 15 * 60 * 1000 // 15分钟长休息
                    else -> 5 * 60 * 1000
                }
            }
            PomodoroPhase.SHORT_BREAK, PomodoroPhase.LONG_BREAK -> {
                // 休息结束，回到工作
                timer.pomodoroPhase = PomodoroPhase.WORK
                timer.totalTime = 25 * 60 * 1000 // 25分钟工作
            }
        }

        timer.currentTime = timer.totalTime
        showPhaseChangeNotification(timer)
    }

    fun pauseTimer() {
        timerState?.let { timer ->
            timer.isRunning = false
            timer.pausedTime = System.currentTimeMillis() - timer.startTime
            timerJob?.cancel()
            updateNotification()
        }
    }

    fun stopTimer() {
        timerState?.let { timer ->
            timer.isRunning = false
            timer.pausedTime = 0
            timer.currentTime = when (timer.type) {
                FocusType.COUNTDOWN -> timer.totalTime
                FocusType.STOPWATCH -> 0
                FocusType.POMODORO -> timer.totalTime
            }
            timerJob?.cancel()
            updateNotification()
        }
    }

    private fun updateNotification() {
        val notification = buildNotification()
        notificationManager?.notify(notificationId, notification)
        startForeground(notificationId, notification)
    }

    private fun buildNotification(): Notification {
        val timer = timerState ?: return Notification()

        val contentText = when (timer.type) {
            FocusType.COUNTDOWN -> "倒计时: ${formatTime(timer.currentTime)}"
            FocusType.STOPWATCH -> "正计时: ${formatTime(timer.currentTime)}"
            FocusType.POMODORO -> {
                val phaseText = when (timer.pomodoroPhase) {
                    PomodoroPhase.WORK -> "工作"
                    PomodoroPhase.SHORT_BREAK -> "短休息"
                    PomodoroPhase.LONG_BREAK -> "长休息"
                }
                "番茄钟($phaseText): ${formatTime(timer.currentTime)}"
            }
        }

        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
        )

        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("计时器运行中")
            .setContentText(contentText)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setOnlyAlertOnce(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build()
    }

    private fun showCompletionNotification(timer: FocusTimer) {
        val notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("计时完成")
            .setContentText(when (timer.type) {
                FocusType.COUNTDOWN -> "倒计时已完成"
                FocusType.POMODORO -> "番茄钟${when (timer.pomodoroPhase) {
                    PomodoroPhase.WORK -> "工作时间"
                    PomodoroPhase.SHORT_BREAK -> "短休息"
                    PomodoroPhase.LONG_BREAK -> "长休息"
                }}已完成"
                else -> "计时已完成"
            })
            .setSmallIcon(R.mipmap.ic_launcher)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()

        notificationManager?.notify(notificationId + 1, notification)
    }

    private fun showPhaseChangeNotification(timer: FocusTimer) {
        val notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("番茄钟阶段切换")
            .setContentText("已切换到${when (timer.pomodoroPhase) {
                PomodoroPhase.WORK -> "工作时间"
                PomodoroPhase.SHORT_BREAK -> "短休息"
                PomodoroPhase.LONG_BREAK -> "长休息"
            }}")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()

        notificationManager?.notify(notificationId + 2, notification)
    }

    private fun formatTime(millis: Long): String {
        val totalSeconds = millis / 1000
        val hours = totalSeconds / 3600
        val minutes = (totalSeconds % 3600) / 60
        val seconds = totalSeconds % 60

        return if (hours > 0) {
            String.format("%02d:%02d:%02d", hours, minutes, seconds)
        } else {
            String.format("%02d:%02d", minutes, seconds)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timerJob?.cancel()
        wakeLock?.release()
        notificationManager?.cancel(notificationId)
    }

}